Vue.component('sidebar-nav', {
    props: {
        currentPage: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            workarea: null,
            currentUser: null,
            isLoading: true
        }
    },
    async created() {
        try {
            console.log('Sidebar component created');
            const userStr = localStorage.getItem(API_CONFIG.USER_KEY);
            if (userStr) {
                this.currentUser = JSON.parse(userStr);
                console.log('Current user:', this.currentUser);
                
                if (this.currentUser.workarea_id) {
                    await this.loadWorkarea();
                } else {
                    console.error('No workarea_id in user data:', this.currentUser);
                }
            }
        } catch (error) {
            console.error('Sidebar initialization failed:', error);
        } finally {
            this.isLoading = false;
        }
    },
    methods: {
        async loadWorkarea() {
            try {
                console.log('Loading workarea for ID:', this.currentUser.workarea_id);
                const response = await window.apiClient.get(`/api/workarea/${this.currentUser.workarea_id}`);
                if (response.data && response.data.ID) {
                    this.workarea = response.data;
                    console.log('Workarea loaded successfully:', this.workarea);
                } else {
                    console.error('Invalid workarea data:', response.data);
                    this.workarea = {
                        ID: this.currentUser.workarea_id,
                        Name: '加载失败',
                        Logo: 'images/default-logo.png'
                    };
                }
            } catch (error) {
                console.error('加载工作区信息失败:', error);
                // 设置默认值
                this.workarea = {
                    ID: this.currentUser.workarea_id,
                    Name: '加载失败',
                    Logo: 'images/default-logo.png'
                };
            }
        },
        handleLogout() {
            console.log('Sidebar logout clicked');
            try {
                // 直接使用 window.auth.logout()
                if (window.auth && typeof window.auth.logout === 'function') {
                    window.auth.logout();
                } else {
                    console.error('Auth module not found, fallback to manual logout');
                    localStorage.removeItem(API_CONFIG.USER_KEY);
                    localStorage.removeItem(API_CONFIG.TOKEN_KEY);
                    window.location.replace(`${API_CONFIG.BASE_URL}/login.html`);
                }
            } catch (error) {
                console.error('Logout failed in sidebar:', error);
                // 强制跳转
                window.location.href = '/login.html';
            }
        },
        navigate(path) {
            const baseUrl = window.API_CONFIG.BASE_URL || '';
            const fullPath = `${baseUrl}${path}`;
            console.log('Navigating to:', fullPath);
            window.location.href = fullPath;
        }
    },
    computed: {
        logoUrl() {
            if (this.workarea?.Logo) {
                return this.workarea.Logo;
            } else if (this.currentUser?.workarea_id) {
                const apiHost = API_CONFIG.API_HOST || 'http://erpapi.hkpublicholiday.com';
                return `${apiHost}/images/workarea_logo_${this.currentUser.workarea_id}.png`;
            }
            return 'images/default-logo.png';
        }
    },
    template: `
        <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="sidebar-header border-bottom" v-if="!isLoading">
                <div class="logo-container">
                    <img :src="logoUrl" 
                         alt="工作区Logo" 
                         class="workarea-logo"
                         @error="$event.target.src='images/default-logo.png'">
                </div>
                <div class="p-3">
                    <div class="small text-muted mb-1" v-if="workarea">
                        工作区ID: {{ workarea.ID || '-' }}
                    </div>
                    <div class="small text-muted mb-1" v-if="workarea">
                        工作区: {{ workarea.Name || '-' }}
                    </div>
                    <div class="small text-muted" v-if="currentUser">
                        用户: {{ currentUser.username || '-' }}
                    </div>
                </div>
            </div>

            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'dashboard' }" href="dashboard.html">
                            <i class="bi bi-speedometer2"></i> 仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'customers' }" href="customers.html">
                            <i class="bi bi-people"></i> 客户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'package-orders' }" href="package-orders.html">
                            <i class="bi bi-cart"></i> 跟团游订单
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'airticket-orders' }" href="airticket-orders.html">
                            <i class="bi bi-ticket-perforated"></i> 机票订单
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'hotel-orders' }" href="hotel-orders.html">
                            <i class="bi bi-building"></i> 酒店订单
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'vehicle-rentals' }" href="vehicle-rentals.html">
                            <i class="bi bi-truck"></i> 租车订单
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'attraction-tickets' }" href="attraction-tickets.html">
                            <i class="bi bi-ticket-perforated"></i> 景点门票
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'meal-orders' }" href="meal-orders.html">
                            <i class="bi bi-cup-straw"></i> 餐饮订单
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'other-orders' }" href="other-orders.html">
                            <i class="bi bi-bag"></i> 其他订单
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'workarea' }" href="workarea.html">
                            <i class="bi bi-building"></i> 公司资料
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'profile' }" href="profile.html">
                            <i class="bi bi-person"></i> 个人资料
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="{ active: currentPage === 'elevy' }" href="elevy-management.html">
                            <i class="bi bi-receipt"></i> Elevy管理
                        </a>
                    </li>
                </ul>

                <hr>
                <div class="px-3">
                    <button type="button" class="btn btn-outline-secondary w-100" @click="handleLogout">
                        <i class="bi bi-box-arrow-right"></i> 退出登录
                    </button>
                </div>
            </div>
        </nav>
    `
}); 